package com.mydemo.workdemo;

import com.alibaba.fastjson.JSON;
import com.mydemo.util.StringSimilarityUtils;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liming1
 */
public class AddressCompare {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("F:\\test.txt");
        Path resultPath = Paths.get("F:\\result.txt");
        BufferedReader bufferedReader = Files.newBufferedReader(path);
        BufferedWriter bufferedWriter = Files.newBufferedWriter(resultPath);

        List<AddressObj> addressObjs = new ArrayList<>();
        List<AddressCompareResult> addressCompareResults = new ArrayList<>();
        String content;
        while ((content = bufferedReader.readLine()) != null) {
            String[] split = content.split(",");
            AddressObj obj = new AddressObj();
            obj.setId(split[0]);
            obj.setAreaCode(split[1]);
            obj.setAddress(split[2]);
            addressObjs.add(obj);
        }
        int length = addressObjs.size();
        int count = 0;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                AddressObj from = addressObjs.get(i);
                AddressObj to = addressObjs.get(j);
                if (!StringUtils.equals(from.getAreaCode(), to.getAreaCode())) {
                    continue;
                }
                float cos = StringSimilarityUtils.cos(from.getAddress(), to.getAddress());
                bufferedWriter.write(String.format("地址1=%s，地址2=%s,相似度=%f", from.getAddress(), to.getAddress(), cos));
                bufferedWriter.newLine();
                if (cos >= 0.8) {
                    AddressCompareResult result = new AddressCompareResult();
                    result.setAddressFrom(from.getAddress());
                    result.setAddressTo(to.getAddress());
                    result.setIdFrom(from.getId());
                    result.setIdTo(to.getId());
                    result.setAreaCode(from.getAreaCode());
                    result.setVal(String.format("%.3f", cos));
                    addressCompareResults.add(result);
                }
            }
        }
        System.out.println(count);
        System.out.println(JSON.toJSONString(addressCompareResults));
        bufferedWriter.close();
        bufferedReader.close();
    }

}